<?php
if (!defined('CMS')) exit;
global$Eleanor, $mainpage;
$Eleanor->module['config'] = include($Eleanor->module['path'] .'config.php');
Eleanor::$Template->queue[] = $Eleanor->module['config']['admintpl'];

$lang = Eleanor::$Language->Load($Eleanor->module['path'] . 'lang_admin-*.php', $Eleanor->module['config']['n']);
Eleanor::LoadOptions($Eleanor->module['config']['opts'], false);

$mainpage = false;

$R = Eleanor::$Db->Query('SELECT COUNT(`status`) FROM `' . P . 'adver` WHERE `status`=-1');
list($cnt) = $R->fetch_row();

$Eleanor->Categories = new Categories_manager;
$Eleanor->Categories->table = $Eleanor->module['config']['c'];
$Eleanor->Categories->deletecb = 'DelCategories';

$Eleanor->module['links']=array(
	'list' => $Eleanor->Url->Prefix(),
	'newlist' => $cnt > 0
	? array(
		#'act'=>isset($_GET['fi'],$_GET['fi']['status']) and $_GET['fi']['status']==-1,
		'link'=>$Eleanor->Url->Construct(array(''=>array('fi'=>array('status'=>-1)))),
		'cnt'=>$cnt,
	)
	: false,
	'add'=>$Eleanor->Url->Construct(array('do'=>'add')),
	'options'=>$Eleanor->Url->Construct(array('do'=>'options')),
	'categories'=>$Eleanor->Url->Construct(array('do'=>'categories')),
	//'addonf'=>$Eleanor->Url->Construct(array('do'=>'addonf'),
);

$Eleanor->post = false;
$Eleanor->ct = array(
	'language' =>  null,
	'name' => array(
		'title' => $lang['tname'],
		'descr' => '',
		'type' => 'edit',
		'bypost' => &$Eleanor->post,
		'options' => array(
			'htmlsafe' => true,
			'addon' => array(
				'tabindex' => 2
			),
		),
	),
);

if (isset($_GET['do']))
	switch ($_GET['do']) {
		case'add':
			if ($_SERVER['REQUEST_METHOD'] == 'POST' and Eleanor::$our_query)
				Save(0);
			else
				AddEdit(0);
		break;
		case'categories':
			$Eleanor->Url->SetPrefix(array('do'=>'categories'),true);
			$c=$Eleanor->Categories->Show();
			if($c) {
				$c=Eleanor::$Template->Categories($c);
				Start();
				echo$c;
			}
		break;
		case'options':
			$Eleanor->Url->SetPrefix(array('do' => 'options'), true);
			$c = $Eleanor->Settings->GetInterface('group', $Eleanor->module['config']['opts']);
			Start();
			echo$c;
		break;
		default:
			ShowAdver();
	}
elseif (isset($_GET['edit']))
{
	$id = (int) $_GET['edit'];
	if ($_SERVER['REQUEST_METHOD'] == 'POST' and Eleanor::$our_query)
		Save($id);
	else
		AddEdit($id);
}
elseif (isset($_GET['delete']))
    Del((int)$_GET['delete']);
elseif (isset($_GET['swap']))
    Swap((int) $_GET['swap']);
elseif (isset($_GET['editt']))
{
    $id = (int) $_GET['editt'];
    if ($_SERVER['REQUEST_METHOD'] == 'POST' and Eleanor::$our_query)
        SaveTag($id);
    else
        AddEditTag($id);
} else
    ShowAdver();

function ShowAdver() {
	global$Eleanor, $title, $mainpage;
	$mainpage = true;
	$title = Eleanor::$Language[$Eleanor->module['config']['n']]['list'];
	$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
	$query = $items = $langs = array();
	$where = '';
	if (!empty($_REQUEST['filter'])) {
		if ($_SERVER['REQUEST_METHOD'] == 'POST')
			$page = 1;
		$query['filter'] = 1;
		if (!empty($_REQUEST['fititle']) and !empty($_REQUEST['fititlet'])) {
			$t = Eleanor::$Db->Escape($_REQUEST['fititle'], false);
			switch ($_REQUEST['fititlet']) {
				case'b':
					$t = ' LIKE \'' . $t . '%\'';
					break;
				case'm':
					$t = ' LIKE \'%' . $t . '%\'';
					break;
				case'e':
					$t = ' LIKE \'%' . $t . '\'';
					break;
				default:
					$t = '=\'' . $t . '\'';
			}
			$query['fititle'] = $_REQUEST['fititle'];
			$query['fititlet'] = $_REQUEST['fititlet'];
			$where.=' AND `title`' . $t;
		}
		if (!empty($_REQUEST['ficategory']))
			if ($_REQUEST['ficategory'] == 'no')
			{
				$query['ficategory'] = '';
				$where.=' AND `cats`=\'\'';
			}
			else
			{
				$query['ficategory'] = (int) $_REQUEST['ficategory'];
				$where.=' AND `cats` LIKE \'%,' . $query['ficategory'] . ',%\'';
			}
		if (!empty($_REQUEST['fistatus']))
		{
			$query['fistatus'] = (int) $_REQUEST['fistatus'];
			$where.=$query['fistatus'] == 1 ? ' AND `status`IN(1,2)' : ' AND `status`=' . $query['fistatus'];
		}
	}
	if (count($query) <= 1)
		unset($query['filter']);
	if (Eleanor::$our_query and isset($_POST['op'], $_POST['mass']) and is_array($_POST['mass']))
		do {
			$in = Eleanor::$Db->In($_POST['mass']);
			switch ($_POST['op']) {
				case'a':
					Eleanor::$Db->Update($Eleanor->module['config']['t'], array('status' => 1), '`id`' . $in);
					Eleanor::$Db->Update($Eleanor->module['config']['tl'], array('lstatus' => 1), '`id`' . $in);
					break;
				case'd':
					Eleanor::$Db->Update($Eleanor->module['config']['t'], array('status' => 0), '`id`' . $in);
					Eleanor::$Db->Update($Eleanor->module['config']['tl'], array('lstatus' => 0), '`id`' . $in);
					break;
				case'k':
					foreach($_POST['mass'] as $v)
						Files::Delete(Eleanor::$root . Eleanor::$uploads.DIRECTORY_SEPARATOR.$Eleanor->module['config']['n'].DIRECTORY_SEPARATOR.(int)$v);
					Eleanor::$Db->Delete(P.'comments','`module`='.$Eleanor->module['id'].' AND `contid`'.Eleanor::$Db->In($_POST['mass']));
					Eleanor::$Db->Delete($Eleanor->module['config']['t'],'`id`'.$in);
					Eleanor::$Db->Delete($Eleanor->module['config']['tl'],'`id`'.$in);
					Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
					break 2;
			}
			Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
		} while (false);

	$R = Eleanor::$Db->Query('SELECT COUNT(`id`) FROM `' . $Eleanor->module['config']['t'] . '` INNER JOIN `' . $Eleanor->module['config']['tl'] . '` USING(`id`) WHERE `language` IN (\'\',\'' . Language::$main . '\')' . $where);
	list($cnt) = $R->fetch_row();
	if ($page <= 0)
		$page = 1;
	if (isset($_GET['new-pp']) and 4 < $pp = (int) $_GET['new-pp'])
		Eleanor::SetCookie('per-page', $pp);
	else
		$pp = abs((int) Eleanor::GetCookie('per-page'));
	if ($pp < 5 or $pp > 500)
		$pp = 50;
	$offset = abs(($page - 1) * $pp);
	if ($cnt and $offset >= $cnt)
		$offset = max(0, $cnt - $pp);
	$sort = isset($_GET['sort']) ? $_GET['sort'] : '';
	if (!in_array($sort, array('id', 'title', 'date', 'author', 'status')))
		$sort = '';
	$so = ($_SERVER['REQUEST_METHOD'] != 'POST' and $sort and isset($_GET['so'])) ? $_GET['so'] : 'desc';
	if ($so != 'asc')
		$so = 'desc';
	if ($sort and ($sort != 'id' or $so != 'asc'))
		$query+=array('sort' => $sort, 'so' => $so);
	else
		$sort = 'id';

	$R = Eleanor::$Db->Query('SELECT `id`,`cats`,`date`,`pinned`,`date`>`pinned` `_pinned`,`author`,`author_id`,`status`,`title` FROM `' . $Eleanor->module['config']['t'] . '` INNER JOIN `' . $Eleanor->module['config']['tl'] . '` USING(`id`) WHERE `language` IN (\'\',\'' . Language::$main . '\')' . $where . ' ORDER BY `' . $sort . '` ' . $so . ' LIMIT ' . $offset . ', ' . $pp);

	while ($arr = $R->fetch_assoc()) {
		$arr['cats'] = $arr['cats'] ? array_unique(explode(',,', trim($arr['cats'], ','))) : array();
		$items[] = $arr;
	}
	$links=array(
		// 'sort_id'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'id','so'=>$qs['sort']=='id' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		// 'sort_title'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'title','so'=>$qs['sort']=='title' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		// 'sort_date'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'date','so'=>$qs['sort']=='date' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		// 'sort_author'=>$Eleanor->Url->Construct(array_merge($qs,array('sort'=>'author','so'=>$qs['sort']=='author' && $qs['so']=='asc' ? 'desc' : 'asc'))),
		// 'form_items'=>$Eleanor->Url->Construct($qs+array('page'=>$page>1 ? $page : false)),
		// 'pp'=>function($n)use($qs){ return$GLOBALS['Eleanor']->Url->Construct($qs+array('new-pp'=>$n)); },
		// 'first_page'=>$Eleanor->Url->Construct($qs),
		// 'pages'=>function($n)use($qs){ return$GLOBALS['Eleanor']->Url->Construct($qs+array('page'=>$n)); },
	);
	$Eleanor->Categories->Init($Eleanor->module['config']['c']);
	$c = Eleanor::$Template->AdverList($items, $cnt, $pp, $query, $page, $sort, $so, $links);
	Start();
	echo$c;
}

function Swap($id) {
	global$Eleanor;
	if (Eleanor::$our_query) {
		$R = Eleanor::$Db->Query('SELECT `pinned`,`status` FROM `' . $Eleanor->module['config']['t'] . '` WHERE `id`=' . $id . ' LIMIT 1');
		if (list($pin, $st) = $R->fetch_row()) {
			if ($st == 0) {
				if ($pin)
					Eleanor::$Db->Update($Eleanor->module['config']['t'], array('!status' => 'IF(`date`>`pinned` AND `date`<=NOW(),1,2)'), '`id`=' . $id . ' LIMIT 1');
				else
					Eleanor::$Db->Update($Eleanor->module['config']['t'], array('status' => 1), '`id`=' . $id . ' LIMIT 1');
			} else {
				Eleanor::$Db->Update($Eleanor->module['config']['t'], array('status' => 0), '`id`=' . $id . ' LIMIT 1');
			}
		}
		$R = Eleanor::$Db->Query('UPDATE `' . $Eleanor->module['config']['t'] . '` INNER JOIN `' . $Eleanor->module['config']['tl'] . '` USING(`id`) SET `lstatus`=`status` WHERE `id`=' . $id);
		Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
	}
	$back = getenv('HTTP_REFERER');
	GoAway($back ? $back . '#it' . $id : true);
}

function AddEdit($id, $error='') {
	global$Eleanor, $title;
	session_start();
	if ($id) {
		$title[] = Eleanor::$Language[$Eleanor->module['config']['n']]['editing'];
		if (!$error) {
			$R = Eleanor::$Db->Query('SELECT *,`date`>`pinned` `_pin` FROM `' . $Eleanor->module['config']['t'] . '` WHERE id=' . $id . ' LIMIT 1');
			if (!$values = $R->fetch_assoc())
				return GoAway(true);
			$values['cats'] = $values['cats'] ? explode(',,', trim($values['cats'], ',')) : array();


			#Служебное
			$values['_maincat'] = reset($values['cats']);
			if ($values['status'] == 2)
				$values['status'] = 1;
			if ($values['_pin'] and $values['pinned'])
				list($values['pinned'], $values['date']) = array($values['date'], $values['pinned']);

			$R = Eleanor::$Db->Query('SELECT * FROM `' . $Eleanor->module['config']['tl'] . '` WHERE `id`=' . $id);
			while ($temp = $R->fetch_assoc()) {
				$values['price'] = $temp['price'] ? $temp['price'] : '';
				$values['rajon'] = $temp['rajon'] ? $temp['rajon'] : '';
				$values['region'] = $temp['region'] ? $temp['region'] : '';
				$values['date_end'] = $temp['date_end'] ? $temp['date_end'] : '';
				$values['telefon'] = $temp['telefon'] ? $temp['telefon'] : '';
				$values['webadres'] = $temp['webadres'] ? $temp['webadres'] : '';
				$values['email'] = $temp['email'] ? $temp['email'] : '';
				$values['name'] = $temp['name'] ? $temp['name'] : '';
				$values['adres'] = $temp['adres'] ? $temp['adres'] : '';
				$values['pasta_index'] = $temp['pasta_index'] ? $temp['pasta_index'] : '';
				$values['text'] = $temp['text'] ? $temp['text'] : '';
				$values['title'] = $temp['title'] ? $temp['title'] : '';
				$values['uri'] = $temp['uri'] ? $temp['uri'] : '';
				$values['meta_title'] = $temp['meta_title'] ? $temp['meta_title'] : '';
				$values['meta_descr'] = $temp['meta_descr'] ? $temp['meta_descr'] : '';
				// $values['pic'] = $temp['pic'] ? $temp['pic'] : '';
			}
			if ($R = Eleanor::$Db->Query('SELECT `path` FROM `'. $Eleanor->module['config']['i'] .'` WHERE `adver_id` = "'. $id .'" ORDER BY `id`')) {
				while ($a = $R->fetch_row()) {
					$values['images'][] = $a[0];
				}
			}
		}
	}
	else
	{
//		$dv = Eleanor::$vars['multilang'] ? array('' => '') : '';
		$values = array(
			'cats' => array(),
			'date' => date('Y-m-d H:i:s'),
			'pinned' => '',
			'author' => Eleanor::$Login->GetUserValue('name', false),
			'author_id' => Eleanor::$Login->GetUserValue('id'),
			'show_detail' => true,
			'reads' => 0,
			'tags' => array('' => ''),
			'status' => 1,
			#Языковые
			'title' => '',
			'text' => '',
			'uri' => '',
			'meta_title' => '',
			'meta_descr' => '',
			#Специальные
			'one_lang' => true,
			'_maincat' => 0,
			'adres'=>'',
			'webadres'=>'',
			'date_end'=>'',
			'pasta_index'=>'',
			'region' => '',
			'rajon' => '',
			'pic' => '',
			'email'=>'',
			'name'=>'',
			'telefon'=>'',
			'price'=>'',
		);
		$title[] = Eleanor::$Language[$Eleanor->module['config']['n']]['adding'];
	}
	if ($error) {
		$bypost = true;
		if ($error === true)
			$error = '';

		$R = Eleanor::$Db->Query('SELECT `pic` FROM `' . $Eleanor->module['config']['tl'] . '` WHERE `id`=' . $id.' LIMIT 1');
		$v = $R->fetch_assoc();
		$values['title'] = isset($_POST['title']) ? (string) $_POST['title'] : '';
		$values['text'] = isset($_POST['text']) ? (string) $_POST['text'] : '';
		$values['uri'] = isset($_POST['uri']) ? (string) $_POST['uri'] : '';
		$values['pinned'] = isset($_POST['pinned']) ? (string) $_POST['pinned'] : '';
		$values['reads'] = isset($_POST['reads']) ? (string) $_POST['reads'] : '';
		$values['date'] = isset($_POST['date']) ? (string) $_POST['date'] : '';
		$values['author_id'] = isset($_POST['author_id']) ? (string) $_POST['author_id'] : '';
		$values['author'] = isset($_POST['author']) ? (string) $_POST['author'] : '';
		$values['date_end'] = isset($_POST['date_end']) ? (string) $_POST['date_end'] : '';
		$values['status'] = isset($_POST['status']) ? (string) $_POST['status'] : '';
		$values['pic'] = isset($v['pic']) ? (string) $v['pic'] : '';
		$values['meta_descr'] = isset($_POST['meta_descr']) ? (string) $_POST['meta_descr'] : '';
		$values['meta_title'] = isset($_POST['meta_title']) ? (string) $_POST['meta_title'] : '';

		$values['price'] = isset($_POST['price']) ? (int) $_POST['price'] : '';
		$values['_maincat'] = isset($_POST['_maincat']) ? (int) $_POST['_maincat'] : 0;
		$values['cats'] = isset($_POST['cats']) ? (array) $_POST['cats'] : array();
		$values['email'] = isset($_POST['email']) ? (string) $_POST['email'] : '';
		$values['city'] = isset($_POST['city']) ? (string) $_POST['city'] : '';
		$values['telefon'] = isset($_POST['telefon']) ? (string) $_POST['telefon'] : '';
		$values['name'] = isset($_POST['name']) ? (string) $_POST['name'] : '';
		$values['pasta_index'] = isset($_POST['pasta_index']) ? (string) $_POST['pasta_index'] : '';
		$values['adres'] = isset($_POST['adres']) ? (string) $_POST['adres'] : '';
		$values['webadres'] = isset($_POST['webadres']) ? (string) $_POST['webadres'] : '';
		$values['region'] = isset($_POST['region']) ? (string) $_POST['region'] : '';
		$values['rajon'] = isset($_POST['rajon']) ? (string) $_POST['rajon'] : '';
	}
	else
		$bypost = false;
	$uploader = $Eleanor->Uploader->Show($id ? $Eleanor->module['config']['n'] . DIRECTORY_SEPARATOR . $id : false);
	$Eleanor->Categories->Init($Eleanor->module['config']['c']);
	$c = Eleanor::$Template->AddEdit($id, $values, $error, $uploader, $bypost);
	Start();
	echo$c;
}

function Save($id) {
	global$Eleanor;
	#Перечень переменных, которые дублируются для языковой таблицы ниже
	$maincat = isset($_POST['_maincat']) ? (int) $_POST['_maincat'] : false;
	$cats = isset($_POST['cats']) ? array_unique((array) $_POST['cats']) : array();
	if ($cats and count($cats) > 1)
	{
		sort($cats, SORT_NUMERIC);
		if ($maincat != $cats[0])
			array_unshift($cats, $maincat ? $maincat : reset($cats));
	}
	$cats = $cats ? ',' . join(',,', $cats) . ',' : '';

	if (Eleanor::$vars['multilang'] and !isset($_POST['one_lang']))
	{
		$langs = (empty($_POST['lang']) or !is_array($_POST['lang'])) ? array() : $_POST['lang'];
		$langs = array_intersect(array_keys(Eleanor::$langs), $langs);
		if (!$langs)
			$langs = array(Language::$main);
	}
	else
		$langs = array('');

	$values = array(
		'cats' => $cats,
		'date' => isset($_POST['date']) ? (string) $_POST['date'] : date('Y-m-d H:i:s'),
		'pinned' => isset($_POST['pinned']) ? (string) $_POST['pinned'] : null,
		'author' => isset($_POST['author']) ? (string) $_POST['author'] : '',
		'author_id' => isset($_POST['author_id']) ? (string) $_POST['author_id'] : 0,
		'reads' => isset($_POST['reads']) ? (int) $_POST['reads'] : '',
		'status' => isset($_POST['status']) ? (int) $_POST['status'] : '',
	);
	if ($da = strtotime($values['date']) and $da > time())
		$values['status'] = 2;

	if ($values['author'] and $values['author_id'] > 0)
	{
		Eleanor::$UsersDb->Query('SELECT `id` FROM `' . USERS_TABLE . '` WHERE `name`=\'' . Eleanor::$Db->Escape($values['author'], false) . '\' LIMIT 1');
		if (Eleanor::$UsersDb->NumRows() > 0)
			list($values['author_id']) = Eleanor::$UsersDb->fetch_row();
		else
			$values['author_id'] = 0;
	}
//	$values['author'] = FilterArrays::Filter($values['author']);

	if ($da and $values['pinned'] and $pin = strtotime($values['pinned']))
	{
		if ($pin < $da)
			return AddEdit($id, Eleanor::$Language[$Eleanor->module['config']['n']]['error_pinned']);
		elseif ($values['status'] >= 1)
			list($values['date'], $values['pinned']) = array($values['pinned'], $values['date']);
	}
	else
		$values['pinned'] = null;



	$GLOBALS['Eleanor']->Editor->imgalt = isset($_POST['title']) ? (string) Eleanor::$POST['title'] : '';
	$lvalues = array(
		'title' => array('' => $GLOBALS['Eleanor']->Editor->imgalt),
		'text' => array('' => $Eleanor->Editor_result->GetHtml('text')),
		'uri' => array('' => isset($_POST['uri']) ? (string) $_POST['uri'] : ''),
		'meta_title' => array('' => isset($_POST['meta_title']) ? (string) Eleanor::$POST['meta_title'] : ''),
		'meta_descr' => array('' => isset($_POST['meta_descr']) ? (string) Eleanor::$POST['meta_descr'] : ''),
	);


	$ml = in_array('', $langs) ? Language::$main : '';
	foreach (array('title', 'text') as $field)
		foreach ($lvalues[$field] as $k => &$v)
			if (!$v and (in_array($k, $langs) or $ml == $k))
				return AddEdit($id, Eleanor::$Language[$Eleanor->module['config']['n']]['empty_' . $field]);

//	foreach ($lvalues['url'] as $k => &$v) {
//		if ($v == '')
//			$v = htmlspecialchars_decode($lvalues['title'][$k], ENT_QUOTES);
//		$v = $Eleanor->Url->Filter($v, $k);
//		$q_and = ' AND `language`=\'' . $k . '\'' . ($id ? ' AND `id`!=' . $id : '');
//		$R = Eleanor::$Db->Query('SELECT `id` FROM `' . $Eleanor->module['config']['t'] . '` INNER JOIN `' . $Eleanor->module['config']['tl'] . '` USING(`id`) WHERE `uri`={0}' . $q_and . ' LIMIT 1', array($v));
//		if (Eleanor::$Db->NumRows() > 0)
//			$v = null;
//	}

	$date = $values['date'];
	$status = $values['status'];
	if ($id) {
		$t = array();

		Eleanor::$Db->Update($Eleanor->module['config']['t'], $values, 'id=' . $id . ' LIMIT 1');
		Eleanor::$Db->Delete($Eleanor->module['config']['tl'], '`id`=' . $id . ' AND `language`' . Eleanor::$Db->In($langs, true));
		#foreach($langs as &$v)
		{
			$values = array(
				'id' => $id,
				'language' => '',
				'title' => $lvalues['title'][''],
				'text' => $lvalues['text'][''],
				'meta_title' => $lvalues['meta_title'][''],
				'meta_descr' => $lvalues['meta_descr'][''],
				'last_mod' => date('Y-m-d H:i:s'),
			);
			$values['uri'] = $lvalues['uri'][''];
			$values['lstatus'] = $status;
			$values['ldate'] = $date;
			$values['lcats'] = $cats;
			$price = isset($_POST['price']) ? (int) $_POST['price'] : 0;
			$email = isset($_POST['email']) ? (string) $_POST['email'] : '';
			$name = isset($_POST['name']) ? (string) $_POST['name'] : '';
			$telefon = isset($_POST['telefon']) ? (string) $_POST['telefon'] : '';
			$city = isset($_POST['city']) ? (string) $_POST['city'] : '';
			$pasta_index = isset($_POST['pasta_index']) ? (string) $_POST['pasta_index'] : '';
			$adres = isset($_POST['adres']) ? (string) $_POST['adres'] : '';
			$rajon = isset($_POST['rajon']) ? (string) $_POST['rajon'] : '';
			$region = isset($_POST['region']) ? (string) $_POST['region'] : '';
			$webadres = isset($_POST['webadres']) ? (string) $_POST['webadres'] : '';
			$dateend = isset($_POST['date_end']) ? (string) $_POST['date_end'] : '';

			$values['price'] = $price;
			$values['city'] = $city;
			$values['telefon'] = $telefon;
			$values['name'] = $name;
			$values['email'] = $email;

			$values['pasta_index'] = $pasta_index;
			$values['adres'] = $adres;
			$values['rajon'] = $rajon;
			$values['region'] = $region;
			$values['webadres'] = $webadres;
			#$time =strtotime("+30 day");
			# $dateend=date("Y-m-d H:i:s",$time);
			$values['date_end'] = $dateend;
			Eleanor::$Db->Replace($Eleanor->module['config']['tl'], $values);
		}
	}
	else
	{
		// Eleanor::$Db->Transaction(); #Все ради аплоадера
		$id = Eleanor::$Db->Insert($Eleanor->module['config']['t'], $values);
		// try
		// {
			// $ft = $Eleanor->Uploader->MoveFiles($Eleanor->module['config']['n'] . DIRECTORY_SEPARATOR . $id);
		// } catch (EE $E)
		// {
			// Eleanor::$Db->Rollback();
			// return AddEdit($id, $E->getMessage());
		// }
		$values = array('id' => array(), 'language' => array(), 'uri' => array(), 'title' => array(), 'text' => array(), 'meta_title' => array(), 'meta_descr' => array());
		foreach ($langs as $v) {
			$values['id'][] = $id;
			$values['last_mod'][] = date('Y-m-d H:i:s');
			$values['lstatus'][] = $status;
			$values['ldate'][] = $date;
			$values['lcats'][] = $cats;
			// if (Eleanor::$vars['multilang']) {
				// $lang = $v ? $v : null;
				// $values['language'][] = $v;

				// $values['url'][] = $lvalues['url'][$lang];
				// $values['title'][] = str_replace($ft['from'], $ft['to'], $lvalues['title'][$lang]);
				// $values['text'][] = str_replace($ft['from'], $ft['to'], $lvalues['text'][$lang]);
				// $values['meta_title'][] = $lvalues['meta_title'][$lang];
				// $values['meta_descr'][] = $lvalues['meta_descr'][$lang];
			// }
			// else
			{
				$values['language'][] = '';
				$values['uri'][] = $lvalues['uri'][''];
				$values['title'][] = str_replace($ft['from'], $ft['to'], $lvalues['title']['']);
				$values['text'][] = str_replace($ft['from'], $ft['to'], $lvalues['text']['']);
				$values['meta_title'][] = $lvalues['meta_title'][''];
				$values['meta_descr'][] = $lvalues['meta_descr'][''];
			}
		}
		Eleanor::$Db->Insert($Eleanor->module['config']['tl'], $values);
		Eleanor::$Db->Commit();
	}
	Eleanor::$Cache->Delete($Eleanor->module['config']['n'] . '_nextrun');
	Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
	GoAway(empty($_POST['back']) ? true : $_POST['back']);
}

function Del($id) {
	global$Eleanor, $title;
	if (!Eleanor::$our_query)
		return GoAway();

	$R = Eleanor::$Db->Query('SELECT `id`,`title` FROM `' . $Eleanor->module['config']['t'] . '` LEFT JOIN `' . $Eleanor->module['config']['tl'] . '` USING(`id`) WHERE `id`=' . $id . ' AND `language` IN (\'\',\'' . Language::$main . '\') LIMIT 1');
	if (!$arr = Eleanor::$Db->fetch_assoc())
		return GoAway(true);

	if (isset($_POST['ok']) && $_POST['ok'])
	{
		Files::Delete(Eleanor::$root . Eleanor::$uploads . DIRECTORY_SEPARATOR . $Eleanor->module['config']['n'] . DIRECTORY_SEPARATOR . $id);

		#$Eleanor->Comments->DeleteComments($_POST['mass']); #ToDo!
		Eleanor::$Db->Delete($Eleanor->module['config']['t'], '`id`=' . $id . ' LIMIT 1');
		Eleanor::$Db->Delete($Eleanor->module['config']['tl'], '`id`=' . $id);
		Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
		GoAway(empty($_POST['back']) ? true : $_POST['back']);
	}
	else
	{
		$title = Eleanor::$Language[$Eleanor->module['config']['n']]['del_confirm'];
		if (isset($_GET['noback']))
			$back = '';
		else
			$back = isset($_POST['back']) ? (string) $_POST['back'] : getenv('HTTP_REFERER');
		$c = Eleanor::$Template->Cover(Eleanor::$Template->Confirm(sprintf(Eleanor::$Language[$Eleanor->module['config']['n']]['submit_del'], $arr['title']), $back));
		Start();
		echo$c;
	}
}

#Служебное

function GetLanguages($arr) {
	global$Eleanor;
	$sel = Eleanor::Option(Eleanor::$Language[$Eleanor->module['config']['n']]['forallt'], '', in_array('', $arr['value']));
	foreach (Eleanor::$langs as $k => &$v)
		$sel.=Eleanor::Option($v['name'], $k, in_array($k, $arr['value']));
	return$sel;
}

function DelCategories($ids) {
	global$Eleanor;
	#К сожалению в MySQL не предусмотрена функция замены по регулярному выражению. Расставляем грабли.
	foreach ($ids as &$v) {
		Eleanor::$Db->Update($Eleanor->module['config']['t'], array('!cats' => 'REPLACE(`cats`,\',' . $v . ',\',\'\')'));
		Eleanor::$Db->Update($Eleanor->module['config']['tl'], array('!lcats' => 'REPLACE(`lcats`,\',' . $v . ',\',\'\')'));
	}
	Eleanor::$Cache->Lib->DeleteByTag($Eleanor->module['config']['n']);
}

?>